/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import controladores.EmpleadoJpaController;
import controladores.IncapacidadJpaController;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.InputMap;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import modelo.Empleado;
import modelo.Incapacidad;

/**
 *
 * @author Ususario
 */
public class GestionIncapacidad extends javax.swing.JInternalFrame {

    List<String> incapacidades = new ArrayList<String>();
    private DefaultTableModel modelo1;
    String datos1[][] = {};
    String columnas1[] = {"Empleado", "Fecha inicio", "Fecha final"};
    boolean nuevo = false;
    EmpleadoJpaController eC = new EmpleadoJpaController();
    IncapacidadJpaController iC = new IncapacidadJpaController();
    DecimalFormat df = new DecimalFormat();
    java.text.SimpleDateFormat sdf; 

    /**
     * Creates new form GestionIncapacidad
     */
    public GestionIncapacidad() {
        initComponents();
        modelo1 = new DefaultTableModel(datos1, columnas1);
        empleadoCombo.removeAllItems();
        List<Empleado> empleados = eC.findEmpleadoEntities();
        for (Empleado empleado : empleados) {
            empleadoCombo.addItem("" + empleado.getIdempleado() + "-" + empleado.getNombre());
        }
        sdf = new java.text.SimpleDateFormat("dd/MM/yyyy");
        List<Incapacidad> incapacidades = iC.findIncapacidadEntities();
        for (int i = 0; i < incapacidades.size(); i++) {
            Incapacidad in = incapacidades.get(i);
            modelo1.addRow(new Object[]{});
            modelo1.setValueAt(in.getEmpleadoIdempleado().getNombre(), i, 0);
            modelo1.setValueAt(sdf.format(in.getFechainicio()), i, 1);
            modelo1.setValueAt(sdf.format(in.getFechafinal()), i, 2);
        }
        masterTable.setModel(modelo1);
        InputMap im = masterTable.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        im.put(KeyStroke.getKeyStroke("DOWN"), "none");
        im.put(KeyStroke.getKeyStroke("UP"), "none");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false;   //Disallow the editing of any cell

            }};
            codigoLabel = new javax.swing.JLabel();
            nombreLabel = new javax.swing.JLabel();
            fechaInicioField = new javax.swing.JTextField();
            fechaFinalField = new javax.swing.JTextField();
            saveButton = new javax.swing.JButton();
            refreshButton = new javax.swing.JButton();
            newButton = new javax.swing.JButton();
            deleteButton = new javax.swing.JButton();
            codigoLabel1 = new javax.swing.JLabel();
            empleadoCombo = new javax.swing.JComboBox();

            setTitle("Gestionar Incapacidades");
            setPreferredSize(new java.awt.Dimension(885, 440));

            jPanel2.setPreferredSize(new java.awt.Dimension(800, 370));

            masterTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Empleado", "Fecha inicio", "Fecha final"
                }
            ) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.String.class, java.lang.String.class
                };
                boolean[] canEdit = new boolean [] {
                    false, false, false
                };

                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
            masterTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            masterTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    masterTableMouseClicked(evt);
                }
            });
            masterScrollPane.setViewportView(masterTable);

            codigoLabel.setText("Fecha inicio:");

            nombreLabel.setText("Fecha final:");

            fechaInicioField.setEnabled(false);

            fechaFinalField.setEnabled(false);

            saveButton.setText("Guardar");
            saveButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    saveButtonActionPerformed(evt);
                }
            });

            refreshButton.setText("Refrescar");
            refreshButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    refreshButtonActionPerformed(evt);
                }
            });

            newButton.setText("Nuevo");
            newButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    newButtonActionPerformed(evt);
                }
            });

            deleteButton.setText("Borrar");
            deleteButton.setEnabled(false);
            deleteButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    deleteButtonActionPerformed(evt);
                }
            });

            codigoLabel1.setText("Empleado:");

            empleadoCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            empleadoCombo.setEnabled(false);

            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                            .addComponent(newButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(deleteButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(refreshButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(saveButton))
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(codigoLabel)
                                .addComponent(nombreLabel)
                                .addComponent(codigoLabel1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(fechaInicioField)
                                .addComponent(fechaFinalField)
                                .addComponent(empleadoCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(codigoLabel1)
                        .addComponent(empleadoCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(codigoLabel)
                        .addComponent(fechaInicioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(nombreLabel)
                        .addComponent(fechaFinalField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(saveButton)
                        .addComponent(refreshButton)
                        .addComponent(deleteButton)
                        .addComponent(newButton))
                    .addContainerGap(23, Short.MAX_VALUE))
            );

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(34, 34, 34)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(35, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(30, Short.MAX_VALUE))
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
    }//GEN-LAST:event_masterTableMouseClicked

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            if (fechaInicioField.getText().trim().equals("") || fechaFinalField.getText().trim().equals("")) {
                JOptionPane.showMessageDialog(null, "Por favor llene todos los campos");
            } else {
                if (!nuevo) {
                    List<Incapacidad> incapacidad0 = iC.findIncapacidadEntities();
                    Incapacidad seleccionado = incapacidad0.get(masterTable.getSelectedRow());
                    //seleccionado.setFechainicio(nombreField.getText().trim().toUpperCase());
                    //seleccionado.setFechafinal(codigoField.getText().trim().toUpperCase());
                    String partes[] = empleadoCombo.getSelectedItem().toString().split("-");
                    String idEmpleado = partes[0];
                    Empleado emp = eC.findEmpleado(idEmpleado);
                    seleccionado.setEmpleadoIdempleado(emp);
                    iC.edit(seleccionado);
                    List<Incapacidad> incapacidades = iC.findIncapacidadEntities();
                    modelo1 = new DefaultTableModel(datos1, columnas1);
                     for (int i = 0; i < incapacidades.size(); i++) {
                        Incapacidad aux = incapacidades.get(i);
                        modelo1.addRow(new Object[]{});
                        modelo1.setValueAt(aux.getEmpleadoIdempleado().getNombre(), i, 0);
                        modelo1.setValueAt(sdf.format(aux.getFechainicio()), i, 1);
                        modelo1.setValueAt(sdf.format(aux.getFechafinal()), i, 2);
                    }
                    masterTable.setModel(modelo1);
                    fechaInicioField.setText("");
                    fechaInicioField.setEnabled(false);
                    fechaFinalField.setText("");
                    fechaFinalField.setEnabled(false);
                    empleadoCombo.setEnabled(false);

                } else {
                    Incapacidad nuevaI = new Incapacidad();
                    String partes[] = empleadoCombo.getSelectedItem().toString().split("-");
                    String idEmpleado = partes[0];
                    Empleado emp = eC.findEmpleado(idEmpleado);
                    nuevaI.setEmpleadoIdempleado(emp);
                    //nuevaI.setFechainicio(nombreField.getText().trim().toUpperCase());
                    //nuevaI.setFechafinal(nombreField.getText().trim().toUpperCase());
                    iC.create(nuevaI);
                    modelo1.addRow(new Object[]{});
                    modelo1.setValueAt(nuevaI.getEmpleadoIdempleado().getNombre(), masterTable.getRowCount() - 1, 0);
                    modelo1.setValueAt(sdf.format(nuevaI.getFechainicio()), masterTable.getRowCount() - 1, 1);
                    modelo1.setValueAt(sdf.format(nuevaI.getFechafinal()), masterTable.getRowCount() - 1, 2);
                    masterTable.setModel(modelo1);
                    fechaInicioField.setText("");
                    fechaInicioField.setEnabled(false);
                    fechaFinalField.setText("");
                    fechaFinalField.setEnabled(false);
                    empleadoCombo.setEnabled(false);
                }
            }

        } catch (Exception rex) {
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        masterTable.clearSelection();
        fechaInicioField.setEnabled(true);
        fechaInicioField.setText("");
        fechaFinalField.setEnabled(true);
        fechaFinalField.setText("");
        empleadoCombo.setEnabled(true);
        nuevo = true;
    }//GEN-LAST:event_newButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        /*List<vista.Banco> toRemove = new ArrayList<vista.Banco>(selected.length);
         for (int idx = 0; idx < selected.length; idx++) {
         vista.Banco b = list.get(masterTable.convertRowIndexToModel(selected[idx]));
         toRemove.add(b);
         entityManager.remove(b);
         }
         list.removeAll(toRemove);*/
    }//GEN-LAST:event_deleteButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel codigoLabel;
    private javax.swing.JLabel codigoLabel1;
    private javax.swing.JButton deleteButton;
    private javax.swing.JComboBox empleadoCombo;
    private javax.swing.JTextField fechaFinalField;
    private javax.swing.JTextField fechaInicioField;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.swing.JLabel nombreLabel;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
}
